import java.util.ArrayList;
import java.util.List;

/**
 * @author kaho
 * @since 2021/3/15
 */
public class _54_螺旋矩阵 {

    /**
     * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
     * @param matrix
     * @return
     */
    public List<Integer> spiralOrder(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        int top = 0, bottom = row-1, left = 0, right = col - 1;

        List<Integer> result = new ArrayList<>();
        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            for (int i = top+1; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            if(top<bottom&&left<right){
                for (int i = right-1; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }

                for (int i = bottom-1; i > top; i--) {
                    result.add(matrix[i][left]);
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return result;
    }
}
